import {
  OrderStatus
} from '../../pages/order/config';
import {
  config
} from '../../config/index';
import {
  ds
} from '../../tools/data'

const _ = ds.cmd

/** 获取订单列表mock数据 */
function mockFetchOrders(params) {
  const {
    delay
  } = require('../_utils/delay');
  const {
    genOrders
  } = require('../../model/order/orderList');

  return delay(200).then(() => genOrders(params));
}

function getOrderStatusCondition(orderStatus) {
  let statusCondi = {
    _id: _.exists(true)
  }
  if (orderStatus == OrderStatus.PENDING_PAYMENT) statusCondi = {
    payStatus: 'wait'
  }
  else if (orderStatus == OrderStatus.PENDING_DELIVERY) statusCondi = {
    status: '待配送'
  }
  else if (orderStatus == OrderStatus.DELIVERY) statusCondi = {
    status: '配送中'
  }
  else if (orderStatus == OrderStatus.COMPLETE) statusCondi = {
    status: '已送达'
  }
  return statusCondi
}

/** 获取订单列表数据 */
export function fetchOrders(params) {
  return new Promise(resolve => {
    const parameters = params.parameter
    const {
      action,
      user,
      pageNum,
      pageSize,
      orderStatus,
      search
    } = parameters
    // console.log(parameters)
    if (action == 'myOrder') {
      loadMyOrders(parameters, resolve)
    } else { // manage
      const role = user.role
      if (role == 'delivery') loadDeliveryOrders(parameters, resolve)
      else if (role == 'master') loadMasterOrders(parameters, resolve)
      else if (role == 'admin') loadAdminOrders(parameters, resolve)
    }
  })
}

async function loadAdminOrders(parameters, resolve) {
  const {
    action,
    user,
    pageNum,
    pageSize,
    orderStatus,
    search,
  } = parameters
  // console.log(parameters)
  const condi = () => {
    let res = {
      _id: _.exists(true)
    }
    if (orderStatus > 0) {
      res = {
        status: _.eq(OrderStatus.getName(orderStatus)),
        ticketInfo: _.exists(false)
      }
    } else if (search.ticket) {
      res.ticketInfo = _.exists(true)
    }

    if (search.orderId) res._id = _.eq(search.orderId)
    if (search.refound) res.refoundInfo = _.exists(true)
    if (search.openId) res._openid = search.openId
    if (search.ticketOrderId) res.ticketOrderId = _.exists(true)
    if (search.shopId && search.shopId != 'all') res.shopId = _.eq(search.shopId)
    if (search.dateRange) res.createTime = _.gte(search.dateRange.start).and(_.lte(search.dateRange.end))
    if (search.goodsId) res.goodsList = _.elemMatch({
      spuId: _.eq(search.goodsId)
    })

    return res
  }

  let resOrders = []
  if (!search.shopId || search.shopId == 'all') {
    resOrders = await ds.coll('orders')
      .where(condi())
      .skip((pageNum - 1) * pageSize)
      .limit(pageSize)
      .orderBy('createTime', 'desc')
      .get()
  } else {
    await wx.cloud.callFunction({
      name: 'searchOrders',
      data: {
        action,
        user,
        pageNum,
        pageSize,
        orderStatus: OrderStatus.getName(orderStatus),
        search,
      }
    }).then(res => {
      resOrders = {
        data: res.result,
        errMsg: res.errMsg
      }
    }).catch(err => {
      console.error(err)
    })
  }

  // console.log(resOrders)
  resolve(resOrders)
}

async function loadMasterOrders(parameters, resolve) {
  const {
    user,
    pageNum,
    pageSize,
    orderStatus,
    search
  } = parameters

  wx.cloud.callFunction({
    name: 'loadMasterOrders',
    data: {
      user: {
        shops: user.shops
      },
      pageNum,
      pageSize,
      orderStatus,
      search
    },
    success: function (res) {
      resolve({
        data: res.result.list,
        errMsg: res.errMsg
      })
    },
    fail: function (err) {
      console.error(err)
    }
  })

  // resolve(resOrders)
}

async function loadMasterOrders0(parameters, resolve) {
  const {
    action,
    user,
    pageNum,
    pageSize,
    ticket,
    ticketOrderId,
    orderStatus,
    search
  } = parameters

  const _ = ds.cmd

  // 配送员所在店的地址->客户
  console.log(new Date().toLocaleTimeString())
  const addr = await ds.getAll('delivery_addr', {
    shop: _.in(user.shops)
  }, {
    _openid: 1
  })
  const openIds = addr.map(ele => {
    return ele._openid
  })

  // 客户->订单
  const condi = () => {
    let res = {}
    if (orderStatus > 0) {
      res = {
        status: OrderStatus.getName(orderStatus),
        _openid: _.in(openIds),
        ticketInfo: _.exists(false)
      }
    } else { // 全部
      res = {
        _openid: _.in(openIds)
      }
      if (search.ticket) res.ticketInfo = _.exists(true)
      if (search.ticketOrderId) res.ticketOrderId = _.exists(true)
    }

    if (search.orderId) res._id = search.orderId
    if (search.openId) res._openid = search.openId;

    return res
  }
  const resOrders = await ds.coll('orders')
    .where(condi())
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .orderBy('createTime', 'desc')
    .get()
  console.log(resOrders)
  resolve(resOrders)

}

function loadMyOrders(parameters, resolve) {
  const {
    action,
    user,
    pageNum,
    pageSize,
    ticket,
    orderStatus,
    search
  } = parameters
  // console.log(ticket, ticket == 'undefined')
  const _ = ds.cmd
  ds.coll('orders')
    .where(_.and([{
      _id: search.orderId ? _.eq(search.orderId) : _.exists(true),
      _openid: user._openid ? _.eq(user._openid) : _.exists(true),
      ticketInfo: _.exists(ticket == 'undefined' ? false : JSON.parse(ticket)) // 水票订单
    }, getOrderStatusCondition(orderStatus)]))
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .orderBy('createTime', 'desc')
    .get()
    .then(res => {
      resolve(res)
    })
}

async function loadDeliveryOrders(parameters, resolve) {
  const {
    user,
    pageNum,
    pageSize,
    orderStatus,
    search
  } = parameters
  wx.cloud.callFunction({
    name: 'loadDeliveryOrders',
    data: {
      user: {
        shops: user.shops,
        _openid: user._openid
      },
      pageNum,
      pageSize,
      orderStatus,
      search
    },
    success: function (res) {
      const list = res.result?.list || []
      resolve({
        data: list,
        errMsg: res.errMsg
      })
    },
    fail: function (err) {
      console.error(err)
    }
  })
}

async function loadDeliveryOrders0(parameters, resolve) {
  const {
    action,
    user,
    pageNum,
    pageSize,
    ticket,
    orderStatus,
    search
  } = parameters
  // console.log(parameters)
  const _ = ds.cmd

  // 配送员所在店的地址->客户
  // const shopId = +user.shop?.id
  const addr = await ds.getAll('delivery_addr', {
    shop: _.in(user.shops)
  })
  const openIds = addr.map(ele => {
    return ele._openid
  })
  // console.log(openIds)

  // 客户->订单
  const condi = () => {
    let res = {}
    if (orderStatus == OrderStatus.PENDING_DELIVERY) {
      res = {
        status: '待配送',
        _openid: _.in(openIds)
      }
    } else if (orderStatus == OrderStatus.DELIVERY) {
      res = {
        status: '配送中',
        deliveryMan: user._openid
      }
    } else if (orderStatus == OrderStatus.COMPLETE) {
      res = {
        status: '已送达',
        deliveryMan: user._openid
      }
    } else { // 全部
      const allDeli = {
          status: '待配送',
          _openid: _.in(openIds)
        },
        myDeli = {
          deliveryMan: user._openid
        }
      if (search.orderId) {
        allDeli._id = search.orderId
        myDeli._id = search.orderId
      }
      res = _.or([allDeli, myDeli])
    }

    if (orderStatus > 0) {
      if (search.orderId) res._id = search.orderId
      if (search.openId) res._openid = search.openId
    }

    return res
  }
  const condiRes = condi()
  const resOrders = await ds.coll('orders')
    .where(_.and([{
        ticketInfo: _.exists(false)
      },
      condiRes
    ]))
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .orderBy('createTime', 'desc')
    .get()
  resolve(resOrders)
}

/** 获取订单列表mock数据 */
function mockFetchOrdersCount(params) {
  const {
    delay
  } = require('../_utils/delay');
  const {
    genOrdersCount
  } = require('../../model/order/orderList');

  return delay().then(() => genOrdersCount(params));
}

/** 获取订单列表统计 */
export function fetchOrdersCount(params) {
  if (config.useMock) {
    return mockFetchOrdersCount(params);
  }

  return new Promise((resolve) => {
    resolve('real api');
  });
}